package cn.yqm.frame.xmlParse;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import cn.yqm.frame.xmlParse.XmlBeans.XmlAction;
import cn.yqm.frame.xmlParse.XmlBeans.XmlBean;
import cn.yqm.frame.xmlParse.XmlBeans.XmlPackage;
import cn.yqm.frame.xmlParse.XmlBeans.XmlResult;

public class ActionXmlUtil {
	
	public static XmlBean parseXml(String xmlPath){
		SAXReader reader = new SAXReader();
		Document document = null;
		try {
			document = reader.read(new File(xmlPath));
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		Element root = document.getRootElement();
		
		//Element xmlConfig = root.element("xmlConfig");
		
		//首先初始化formBean节点
		Map<String, String> beanMap = new HashMap<String, String>();
		List<Element> beans = root.element("formBean").elements("bean");
		for (Element bean : beans) {
			beanMap.put(bean.attributeValue("id"), bean.attributeValue("class"));
		}
		
		List<Element> packages = root.elements("package");
		XmlBean xmlBean = new XmlBean();

		List<XmlPackage> xmlPackages = new ArrayList<XmlPackage>();
		for (Element elementPackage : packages) {
			XmlPackage xmlPackage = new XmlPackage();
			xmlPackage.setName(elementPackage.attributeValue("name"));
			xmlPackage.setNamespace(elementPackage.attributeValue("namespace"));
			
			List<XmlAction> xmlActions = new ArrayList<XmlAction>();
			List<Element> actions = elementPackage.elements("action");
			for (Element elementAction : actions) {
				XmlAction xmlAction = new XmlAction();
				xmlAction.setName(elementAction.attributeValue("name"));
				xmlAction.setClassPath(elementAction.attributeValue("class"));
				
				//如果存在bean属性，则取formbean中对应的bean节点
				if(elementAction.attributeValue("bean")!=null){
					String beanId = elementAction.attributeValue("bean");
					if(beanMap.get(beanId)!=null){
						xmlAction.setBeanClass(beanMap.get(beanId));
					}
				}
				
				List<XmlResult> xmlResults = new ArrayList<XmlResult>();
				List<Element> results = elementAction.elements("result");
				for (Element elementResult : results) {
					XmlResult xmlResult = new XmlResult();
					xmlResult.setName(elementResult.attributeValue("name"));
					xmlResult.setForwardPath(elementResult.getStringValue());
					xmlResults.add(xmlResult);
				}
				xmlAction.setResults(xmlResults);
				
				xmlActions.add(xmlAction);
			}
			xmlPackage.setXmlActions(xmlActions);
			
			xmlPackages.add(xmlPackage);
		}
		xmlBean.setPackages(xmlPackages);
		
		return xmlBean;
	}
}
